package alwv.database;

import java.sql.*;
/**
* Encapsulate a JDBC database connection along with a method that ,
* given a SQL query as a string , returns a ResultSetTableModel object
* suitable for display in a JTable
 * 
 * @author Tom Naps
 * Taken from CS361 lecture on April 13th 2012
 * Modified to accept a connection generated somewhere else.
 * UWOSHKOSH
**/
public class ResultSetTableModelFactory {
    Connection connection;
    /** The constructor method uses the argument to create db Connection */
    public ResultSetTableModelFactory (Connection c) throws ClassNotFoundException , SQLException
    {
        // This is the only aspect of the demo that ties it to Derby
        connection = c;
    }
    
    
    /**
    * Takes a SQL query , pass it to the database , obtain the results
    * as a ResultSet , and return a ResultSetTableModel object
    **/
    public ResultSetTableModel getResultSetTableModel (String query) throws SQLException {
        if (connection == null)
        throw new IllegalStateException ("Connection already closed.");
        // Create a Statement object that will be used to execute the
        // query . The arguments specify that the returned ResultSet
        // will be scrollable and read - only . The scrollable property
        // is a necessary kludge to determine the number of rows in
        // the table / ResultSet
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        // Run the query , creating a ResultSet
        ResultSet r = statement.executeQuery(query);
        // Create and return a TableModel for the ResultSet
        return new ResultSetTableModel(r);
    }
}
